﻿var User_Base = new Class({
	id:null,key:null,nick:'',avatar:null,
	initialize: function(){
		this.readCook();
		// if need login, do login
		var search = window.location.search.replace('?','');
		var params = search.parseQueryString();
		if($defined(params.login) && params.login=='1') this.login();
		// timer
		//this._timer = this.refresh.periodical(this._refreshPeriod,this);
	},
	readCook: function(){
		var uid = Cookie.read("uid"); this.id = parseInt(uid);
		var uik = Cookie.read('uik'); this.key = uik;
		var unick = Cookie.read('unick'); if($chk2(unick)) this.nick = unick;
	},
	delCook: function(){
		Cookie.dispose("uid",{path:'/'});
		Cookie.dispose('uik',{path:'/'});
		Cookie.dispose('unick',{path:'/'});
	},
	logged: function(){ return $chk2(this.id); },
	login: function(){
		var self = this;
		if(this.logged()) return;
		var box = new PromptBox({controls:[{type:'text',title:'用户名：',id:'username','cssClass':'shortinput'},
											{type:'password',title:'密码：',id:'password','cssClass':'shortinput'}
										],title:'登录',modal:true,
			action:function(result){
				var usrname = result.username; var pass = result.password; var password = MD5(pass);
				var params = String.format('username={0}&password={1}',usrname,password);
				new echoAjax({url:'/alogin/',params:params,reLoad:true}).fire();
			}
		});
	},
	logout: function(){
		this.delCook();
		window.location.reload();
	},
	refresh: function(){
		if(!this.logged()) return;
		var refreshtime = Cookie.read('refresh'); var tm = new Date().getTime();
		if(!$chk2(refreshtime) || tm-refreshtime > this._refreshPeriod){
			new echoAjax({url:'/user/refresh/',params:'',onSuccess:function(){},onFailure:function(){}}).fire();
			Cookie.write('refresh',tm,{path:'/'})
		}
	},
	nickname: function(obj){
		var nick = obj || '';
		var box = new PromptBox({controls:[{type:'text',value:nick,title:'昵称：',id:'nick_name','cssClass':'shortinput'}],title:'输入昵称',modal:true,
			action:function(result){
				var text = JSON.encode(result);
				new echoAjax({url:'/user/change/',params:String.encode('nick='+result.nick_name),
							onSuccess: function(response){
								if(response.result==true || response.result=='true'){
									$('user_nick').innerHTML = response.message;
								}else new MsgBox({message:response.message});
							}
				}).fire();
			}
		});
	}
});
var User = new User_Base();
